<?php
/**
 * This is a class for printing MixiEcho data to a CUI interface extends MixiEcho to obtain data
 */ 
class ConsolePrinter extends MixiEcho
{
	public $filterManager;
	
	/**
	 * Construct the with the filter manager to filter data
	 */
	public function __construct($filterManager)
	{
		$this->filterManager = $filterManager;		
		parent::__construct("ConsolePrinter", "authenticate");
		
		echo "=============================================\n";
		echo "            EchoNav 1.0 CLI Printer          \n";
		echo "=============================================\n\n";
	}
	
	public function outputEchos()
	{
		$echos = $this->getEchos($this->filterManager);

		// There's no echos.  First time user or tried to access a page with none.		
		if(!$echos)
			return false;
		
		foreach($echos as $echo)
		{
			if($echo['filter_output'])
			{
				$output_format = constant($echo['filter_output'] . '_FORMAT');
				
				if(!$output_format)
				{
					$output_format = ECHO_FORMAT;
				}
			}
			else
			{
				$output_format = ECHO_FORMAT;
			}
			
			$echo_output = str_replace(
				array(
					'@comment',
					'@nickname',
					'@replyto',
					'@selfnick'
				),
				array(
					$echo['comment'],
					$echo['nickname'],
					$echo['replyto'],
					$echo['selfnick']
				),
				$output_format
			);
			
			echo self::charset_convert($echo_output);
		}
		
		echo self::charset_convert("全部: " . count($echos) . "エコー\n\n");
		
		echo self::charset_convert("インターキーでプログラムを終了します.\n\n");
		$this->get_stdin();
	}
	
	public static function charset_convert($text, $charset=ECHO_CHARSET)
	{
		return mb_convert_encoding($text, $charset, 'auto');
	}
	
	public static function authenticate()
	{
		echo self::charset_convert("ユーザーネーム： ");
		
		$username = self::get_stdin();
		if(!$username)
		{
			throw new LoginFailure("001 - username_empty");
		}
		
		echo self::charset_convert("パスワード: ");
		$password = self::get_stdin();
		if(!$password)
		{
			throw new LoginFailure("001 - password_empty");
		}
		echo "\n";
		return array($username, $password);
	}
	
	public static function get_stdin()
	{
		$input = fopen("php://stdin", 'r');
		$response = trim(fgets($input, 1024));
		fclose($input);
		return $response;
	}
}
?>
